/*
*  Copyright 2019-2020
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.qp.basics.admin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qp.basics.admin.repository.OauthClientDetailRepository;
import com.qp.basics.admin.service.OauthClientDetailService;
import com.qp.basics.admin.service.dto.OauthClientDetailQueryCriteria;
import com.qp.basics.common.domain.OauthClientDetail;

import com.qp.basics.common.service.dto.OauthClientDetailDto;
import com.qp.basics.common.service.mapstruct.OauthClientDetailMapper;
import com.qp.basics.common.utils.FileUtil;
import com.qp.basics.common.utils.PageUtil;
import com.qp.basics.common.utils.QueryHelp;
import com.qp.basics.common.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
*
* @description 服务实现
**/
@Service
@RequiredArgsConstructor
public class OauthClientDetailServiceImpl implements OauthClientDetailService {

    @Autowired
    PasswordEncoder passwordEncoder;

    private final OauthClientDetailRepository oauthClientDetailRepository;
    private final OauthClientDetailMapper oauthClientDetailMapper;

    @Override
    public Map<String,Object> queryAll(OauthClientDetailQueryCriteria criteria, Pageable pageable){
        Page<OauthClientDetail> page = oauthClientDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(oauthClientDetailMapper::toDto));
    }

    @Override
    public List<OauthClientDetailDto> queryAll(OauthClientDetailQueryCriteria criteria){
        return oauthClientDetailMapper.toDto(oauthClientDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public OauthClientDetailDto findById(Long id) {
        OauthClientDetail oauthClientDetail = oauthClientDetailRepository.findById(id).orElseGet(OauthClientDetail::new);
        ValidationUtil.isNull(oauthClientDetail.getId(),"OauthClientDetail","id",id);
        return oauthClientDetailMapper.toDto(oauthClientDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OauthClientDetailDto create(OauthClientDetail resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        resources.setClientSecret(passwordEncoder.encode(resources.getClientSecret()));
        return oauthClientDetailMapper.toDto(oauthClientDetailRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(OauthClientDetail resources) {
        OauthClientDetail oauthClientDetail = oauthClientDetailRepository.findById(resources.getId()).orElseGet(OauthClientDetail::new);
        ValidationUtil.isNull( oauthClientDetail.getId(),"OauthClientDetail","id",resources.getId());
        resources.setId(oauthClientDetail.getId());
        resources.setClientSecret(oauthClientDetail.getClientSecret());
        oauthClientDetailRepository.save(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            oauthClientDetailRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<OauthClientDetailDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (OauthClientDetailDto oauthClientDetail : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目名称", oauthClientDetail.getProjectName());
            map.put("供应商名称", oauthClientDetail.getSupplierName());
            map.put("联系人", oauthClientDetail.getContact());
            map.put("联系电话", oauthClientDetail.getPhone());
            map.put("入口网址", oauthClientDetail.getUrl());
            map.put("描述", oauthClientDetail.getDescription());
            map.put("客户端Id", oauthClientDetail.getClientId());
            map.put("客户端密钥", oauthClientDetail.getClientSecret());
            map.put("资源id集合", oauthClientDetail.getResourceIds());
            map.put("权限范围", oauthClientDetail.getScope());
            map.put("授权方式", oauthClientDetail.getAuthorizedGrantTypes());
            map.put("重定向URI", oauthClientDetail.getWebServerRedirectUri());
            map.put("权限值", oauthClientDetail.getAuthorities());
            map.put("access_token有效时间(s)", oauthClientDetail.getAccessTokenValidity());
            map.put("refresh_token的有效时间值(s)", oauthClientDetail.getRefreshTokenValidity());
            map.put("预留字段", oauthClientDetail.getAdditionalInformation());
            map.put("用户是否自动Approval操作", oauthClientDetail.getAutoapprove());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public JSONObject importExcel(MultipartFile file) {
        JSONObject res=new JSONObject();
/**
        try (InputStream is = file.getInputStream()) {
            ExcelX ex = new ExcelX(is);
            List<Map> l = ex.excelToMapList(0);
            int count=0;
            for (int i = 0; i < l.size(); i++) {
                Map m = l.get(i);
                Object t = m.get("id");
                if (t == null || "".equals(t)) {
                    continue;
                }
                OauthClientDetail q = new OauthClientDetail();
            String projectName = ImortExportUtil.toStr(m.get("项目名称"));
            q.setProjectName(projectName);
            String supplierName = ImortExportUtil.toStr(m.get("供应商名称"));
            q.setSupplierName(supplierName);
            String contact = ImortExportUtil.toStr(m.get("联系人"));
            q.setContact(contact);
            String phone = ImortExportUtil.toStr(m.get("联系电话"));
            q.setPhone(phone);
            String url = ImortExportUtil.toStr(m.get("入口网址"));
            q.setUrl(url);
            String description = ImortExportUtil.toStr(m.get("描述"));
            q.setDescription(description);
            String clientId = ImortExportUtil.toStr(m.get("客户端Id"));
            q.setClientId(clientId);
            String clientSecret = ImortExportUtil.toStr(m.get("客户端密钥"));
            q.setClientSecret(clientSecret);
            String resourceIds = ImortExportUtil.toStr(m.get("资源id集合"));
            q.setResourceIds(resourceIds);
            String scope = ImortExportUtil.toStr(m.get("权限范围"));
            q.setScope(scope);
            String authorizedGrantTypes = ImortExportUtil.toStr(m.get("授权方式"));
            q.setAuthorizedGrantTypes(authorizedGrantTypes);
            String webServerRedirectUri = ImortExportUtil.toStr(m.get("重定向URI"));
            q.setWebServerRedirectUri(webServerRedirectUri);
            String authorities = ImortExportUtil.toStr(m.get("权限值"));
            q.setAuthorities(authorities);
            String accessTokenValidity = ImortExportUtil.toStr(m.get("access_token有效时间(s)"));
            q.setAccessTokenValidity(accessTokenValidity);
            String refreshTokenValidity = ImortExportUtil.toStr(m.get("refresh_token的有效时间值(s)"));
            q.setRefreshTokenValidity(refreshTokenValidity);
            String additionalInformation = ImortExportUtil.toStr(m.get("预留字段"));
            q.setAdditionalInformation(additionalInformation);
            String autoapprove = ImortExportUtil.toStr(m.get("用户是否自动Approval操作"));
            q.setAutoapprove(autoapprove);
                q = oauthClientDetailRepository.save(q);
                count++;
            }
            res.put("msg","导入成功：共导入"+count+"条");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("msg","导入失败："+e.getMessage());
        }
            **/
        return res;
    }
}
